package token

import (
	"context"
	"strconv"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateTokenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateTokenLogic {
	return &CreateTokenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Token management
func (l *CreateTokenLogic) CreateToken(in *backend.TokenInfo) (*backend.BaseUUIDResp, error) {
	var token model.SysToken
	if in.Uuid != nil {
		token.UUID = *in.Uuid
	}
	if in.Token != nil {
		token.Token = *in.Token
	}
	if in.Source != nil {
		token.Source = *in.Source
	}
	if in.Status != nil {
		token.Status = uint8(*in.Status)
	} else {
		token.Status = uint8(globalkey.StatusEnabled)
	}
	if in.ExpiredAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.ExpiredAt); err == nil {
			token.ExpiredAt = null.TimeFrom(localTime)
		}
	}
	now := time.Now()
	token.CreatedAt = now
	token.UpdatedAt = now
	err := l.svcCtx.SysToken.Insert(l.ctx, nil, &token)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseUUIDResp{
		Id:  strconv.FormatInt(int64(token.ID), 10),
		Msg: i18n.CreateSuccess,
	}, nil
}
